<template>
    <!--添加任务模态框-->
    <n-modal
        v-model:show="showModal"
        :mask-closable="false"
        preset="dialog"
        :title="state.type==='add'?'新增任务':'修改任务'"
        @afterLeave="closed"
        :z-index="3"
    >
        <n-form
            ref="formRef"
            :model="newTask"
            :rules="rules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
            size="medium"
            :style="{
                    maxWidth: '640px'
                }"
        >
            <!--任务名称-->
            <n-form-item label="所属项目" path="name" v-show="state.type ==='modified'">
                <n-select
                    v-model:value="newTask.project_id"
                    placeholder="请选择所属项目"
                    :style="{width: '100%'}"
                    :options="superAdmin.taskQuestionBank.enable"
                    label-field="name"
                    value-field="id"
                    children-field="noChildren"
                />
            </n-form-item>
            <!--任务名称-->
            <n-form-item label="任务名称" path="name">
                <n-input v-model:value="newTask.name" type="text" placeholder="任务名称"/>
            </n-form-item>
            <!--任务描述-->
            <n-form-item label="任务描述" path="describe">
                <n-input v-model:value="newTask.describe" type="textarea" placeholder="项目描述"/>
            </n-form-item>
            <!--任务需完成-->
            <n-form-item label="任务需完成" path="radioGroupValue1">
                <n-radio-group v-model:value="newTask.rating_type" name="radioGroup">
                    <n-space>
                        <n-radio value="p">
                            图
                        </n-radio>
                        <n-radio value="t">
                            表
                        </n-radio>
                        <n-radio value="tp">
                            图+表
                        </n-radio>
                    </n-space>
                </n-radio-group>
            </n-form-item>
            <!--评分权重-->
            <n-form-item label="评分权重" path="sliderValue" v-show="newTask.rating_type==='tp'">
                <n-slider v-model:value="newTask.picture_weight" :step="1" :format-tooltip="formatTooltip"/>
            </n-form-item>
            <!--图形对比评分表-->
            <n-form-item label="图形对比评分表" path="pictureFile" v-show="newTask.rating_type!=='t'">
                <n-upload
                    @change="handleChangePictureFile"
                    :default-upload="false"
                    :max="1"
                    accept=".jpg,.png"
                    v-model:default-file-list="uploadList.pictureList"
                >
                    <n-button>上传图像</n-button>
                </n-upload>
            </n-form-item>
            <!--表格对比评分表-->
            <n-form-item label="表格对比评分表" path="tableFile" v-show="newTask.rating_type!=='p'">
                <n-upload
                    @change="handleChangeTableFile"
                    :default-upload="false"
                    :max="1"
                    accept=".csv,.xlsx"
                    v-model:default-file-list="uploadList.tableList"
                >
                    <n-button>上传表格</n-button>
                </n-upload>
            </n-form-item>
            <!--选择题目-->
            <n-form-item label="选择题目" path="task_analysis_questions_id">
                <n-button @click="setActive">选择题目</n-button>
                <!-- 选择题目抽屉-->
                <n-drawer v-model:show="active" :width="700" :placement="'right'" :z-index="4">
                    <n-drawer-content title="选择题目">
                        <n-checkbox-group v-model:value="newTask.task_analysis_questions_id">
                            <div v-for="index in questionBank">
                                <div>
                                    <!--勾选框与标题-->
                                    <n-checkbox
                                        :value="index.number"
                                        :label="index.number + index['question']"
                                    />
                                    <span> 答案: {{ index.answer }}</span>
                                    <br>
                                    <span>{{ 'A: ' + index.A }}</span><br>
                                    <span>{{ 'B: ' + index.B }}</span><br>
                                    <span>{{ 'C: ' + index.C }}</span><br>
                                    <span>{{ 'D: ' + index.D }}</span>
                                    <hr>
                                </div>
                            </div>
                        </n-checkbox-group>
                    </n-drawer-content>
                </n-drawer>
            </n-form-item>
            <!--难易程度-->
            <n-form-item label="难易程度" path="radioGroupValue2">
                <n-radio-group v-model:value="newTask.difficulty" name="radioGroup">
                    <n-space>
                        <n-radio value="简单">
                            简单
                        </n-radio>
                        <n-radio value="适中">
                            适中
                        </n-radio>
                        <n-radio value="难">
                            难
                        </n-radio>
                    </n-space>
                </n-radio-group>
            </n-form-item>
            <!--任务资源-->
            <n-form-item label="任务资源" path="taskResources">
                <n-input v-model:value="newTask.task_resources" type="text" placeholder="任务资源"/>
            </n-form-item>
            <!--任务数据源-->
            <n-form-item label="任务数据源" path="data_source_id">
                <n-cascader
                    v-model:value="newTask.data_source_id"
                    multiple
                    clearable
                    placeholder="任务数据源"
                    max-tag-count="responsive"
                    expand-trigger="hover"
                    :options="superAdmin.getDataSourceTree"
                    :cascade="true"
                    check-strategy="child"
                    :show-path="true"
                    :filterable="true"
                    @update:value="handleUpdateValue"
                />
            </n-form-item>
            <!--表格自动评分-->
            <n-form-item label="表格自动评分" path="auto_scoring">
                <n-switch v-model:value="newTask.auto_scoring"/>
            </n-form-item>
            <!--两个按钮-->
            <div style="display: flex; justify-content: flex-end">
                <n-button @click="onNegativeClick">
                    取消
                </n-button>
                <n-button type="primary" @click="handleValidateButtonClick">
                    确定
                </n-button>
            </div>
        </n-form>

    </n-modal>
</template>

<script setup>
import workApi from "@/http/workApi";
import {useSuperAdminStore} from "@/stores/superAdmin";

const superAdmin = useSuperAdminStore()
const props = defineProps(['setKey'])
const showModal = ref(false)
const active = ref(false)
const formRef = ref(null)
// 状态  默认为新增任务
const state = reactive({
    type: 'add',
    apiMethod: 'post',
})

// 题库
const questionBank = ref(null)
const setShowModal = (projectId = null) => {
    newTask.value.project_id = projectId
    showModal.value = !showModal.value
    // 获取题库
    workApi.post('super_admin/question', {
        project_id: projectId
    }).then((res) => {
        if (res['success']) {
            questionBank.value = res.data[0].children.map((s) => {
                s.isChecked = -s.number
                return s
            });
        }
    })
}
const setActive = () => {
    active.value = !active.value
}
const newTask = ref({
    project_id: null,
    name: null,
    describe: null,
    task_analysis_questions_id: [],
    task_resources: 'https://tch.metaskillcloud.com/home',
    difficulty: '简单',
    rating_type: 'tp',
    auto_scoring: false,
    picture_weight: 50,
    picture_file: null,
    table_weight: 50,
    table_file: null,
    data_source_id: [],
})
// 验证规则
const rules = {
    name: {
        required: true,
        trigger: ['blur'],
        message: '未填'
    },
    task_analysis_questions_id: {
        required: true,
        type: 'array',
        trigger: ['blur'],
        message: '未填'
    },
    task_resources: {
        required: true,
        trigger: ['blur'],
        message: '未填'
    },
    pictureFile: {
        required: true,
        validator() {
            return newTask.value.rating_type === 't' || !!uploadList.pictureList.length
        },
        trigger: ['blur'],
        message: '未填'
    },
    tableFile: {
        required: true,
        validator() {
            return newTask.value.rating_type === 'p' || !!uploadList.tableList.length
        },
        trigger: ['blur'],
        message: '未填'
    },
    data_source_id: {
        required: true,
        type: 'array',
        trigger: ['blur'],
        message: '未填'
    },

};
// 评分权重自定义tooltip
const formatTooltip = () => {
    newTask.value.table_weight = 100 - newTask.value.picture_weight
    return '图像权重:' + newTask.value.picture_weight + '% 表格权重:' + newTask.value.table_weight + '%'
}
// 上传列表
const uploadList = reactive({
    // 图片
    pictureList: [],
    // 表格
    tableList: [],
})
// 自定义上传图片文件
const handleChangePictureFile = (options) => {
    // 文件信息添加到上传列表中
    uploadList.pictureList = options.fileList
    // 将图片文件放到newTask中
    newTask.value.picture_file = options.file.file

}
// 自定义上传表格文件
const handleChangeTableFile = (options) => {
    // 文件信息添加到上传列表中
    uploadList.tableList = options.fileList
    // 将表格文件放到newTask中
    newTask.value.table_file = options.file.file
}
const handleUpdateValue = (value, options) => {
    console.log(value, options);
}

// 点击取消
const onNegativeClick = () => {
    showModal.value = false
}
// 点击确定
const handleValidateButtonClick = () => {
    // 验证是否填写
    formRef.value?.validate((errors) => {
        if (!errors) {

            // 创建表单
            const formData = new FormData();
            // 循环newTask
            for (let key in newTask.value) {
                if (newTask.value[key] === null) {
                    continue
                }
                if (key === 'task_analysis_questions_id' || key === 'data_source_id') {
                    // 将题目列表转换成字符串添加进表单
                    formData.append(
                        key,
                        '[' + newTask.value[key] + ']'
                    );
                } else {
                    // 其他的正常添加进表单
                    formData.append(
                        key,
                        newTask.value[key]
                    );
                }
            }

            workApi({
                method: state.apiMethod,
                url: 'super_admin/task',
                data: formData,
                onUploadProgress: progressEvent => {
                    // 上传进度百分比
                    let percent = (progressEvent.loaded / progressEvent.total * 100 | 0)
                    // 设置为上传状态 设置上传进度百分比
                    if (newTask.value.rating_type !== 't') {
                        uploadList.pictureList[0].status = 'uploading';
                        uploadList.pictureList[0].percentage = percent
                    }
                    if (newTask.value.rating_type !== "p") {
                        uploadList.tableList[0].status = 'uploading';
                        uploadList.tableList[0].percentage = percent
                    }
                },
            }).then(() => {
                if (newTask.value.rating_type !== 't') {
                    uploadList.pictureList[0].status = 'finished'
                }
                if (newTask.value.rating_type !== "p") {
                    uploadList.tableList[0].status = 'finished'
                }
                superAdmin.updateTaskQuestionBank()
                closed()
            }).catch((error) => {
                console.log(error)
            });
        } else {
            window.$message.error('验证失败')
        }
    })
}
const closed = () => {
    console.log(1)
    props.setKey()
}
// 父组件使用修改任务
const openModifiedTask = (data) => {
    state.type = 'modified'
    state.apiMethod = 'put'
    // 改变数据
    newTask.value.id = data.task_id
    newTask.value.project_id = data.project_id
    newTask.value.name = data.name
    newTask.value.describe = data.describe
    newTask.value.task_resources = data.task_resources
    newTask.value.difficulty = data.difficulty
    newTask.value.rating_type = data.rating_type
    newTask.value.auto_scoring = data.auto_scoring
    newTask.value.picture_weight = data.picture_weight
    newTask.value.table_weight = data.table_weight
    newTask.value.data_source_id = data.data_source_id


    // 改变数据---题目
    data['task_questions'].map((s) => {
        newTask.value.task_analysis_questions_id.push(s.number)
    })
    // 改变数据---文件列表
    let pictureFileText = data.picture_file.split('_')
    let tableFileText = data.table_file.split('_')
    uploadList.pictureList.push({
        id: data.picture_file,
        name: pictureFileText[pictureFileText.length - 1],
        status: 'finished',
        url: data.table_file
    })
    uploadList.tableList.push({
        id: data.table_file,
        name: tableFileText[tableFileText.length - 1],
        status: 'finished',
        url: data.table_file
    })
    // 展示
    setShowModal(data.project_id)
}

defineExpose({
    setShowModal,
    openModifiedTask
})

</script>

<style scoped lang="less">
.n-button {
    margin: 15px;
}
</style>